<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoListHearder @addList="addList"></TodoListHearder>

    <!-- 主体部分 -->
    <TodoListBody :list="showType" @checked="checked" @del="del" @changeAll="changeAll"></TodoListBody>

    <!-- 底部部分 -->
    <TodoListFooter
      :sum="sum"
      :clearBtn="clearBtn"
      @clearAll="clearAll"
      :type="type"
      @changeType="changeType"
    ></TodoListFooter>
  </section>
</template>

<script>
import TodoListHearder from './components/TodoListHeader.vue'
import TodoListBody from './components/TodoListBody.vue'
import TodoListFooter from './components/TodoListFooter.vue'
export default {
  components:{
    TodoListHearder,
    TodoListBody,
    TodoListFooter
  },
  data(){
    return {
      list:JSON.parse(localStorage.getItem('list'))||[
        {id:1,content:'读万卷书',flag:true},
         {id:2,content:'行万里路',flag:false},
      ],
      type:'all'
    }
  },
  methods:{
    addList(value){
      this.list=[...this.list,{id:+new Date(),content:value,flag:false}]
    },
    checked(id,flag){
      this.list.forEach(item=> {
        if (item.id===id) {
          item.flag=flag
        }
      })
    },
    changeAll(){
      this.list.forEach(item=> item.flag=true)
    },
    del(id){
    this.list.find(item=>item.id===id).flag&&  (this.list= this.list.filter(item=> item.id!==id))

    },
    clearAll(){
      this.list=this.list.filter(item=> !item.flag)
    },changeType(value){
      this.type=value
    }
  },
  computed:{
    sum(){
      return this.list.filter(item=> !item.flag).length
    },
    clearBtn(){
      return this.list.some(item=> item.flag)
    },showType(){
      switch(this.type){
        case 'all':
          return this.list
        case 'active':
           return this.list.filter(item=> !item.flag)
        case 'completed':
           return this.list.filter(item=> item.flag)
        default :
        return this.list

      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(nv){
        localStorage.setItem('list',JSON.stringify(nv))
      }
    }
  }
}
</script>

<style></style>
